package com.lsl.controller;

import com.lsl.bean.User;
import com.lsl.service.UserService;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/selectAll")
    @ResponseBody
    public List<User> selectAll(){
        return userService.selectAll();
    }

    @RequestMapping("/selectById")
    @ResponseBody
    public User selectById(int id){
        return userService.selectById(id);
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public int deleteById(int id){
        return userService.deleteById(id);
    }

    @RequestMapping("/insertInfo")
    @ResponseBody
    public int insertInfo(User user){
        return userService.insertInfo(user);
    }

    @RequestMapping("/updateById")
    @ResponseBody
    public int updateById(User user){
        return userService.updateById(user);
    }

    @RequestMapping(value = "/test1")
    public String test1(Model model){
        List<User> users = userService.selectAll();
        model.addAttribute("users",users);
        return "test1";
    }

    @RequestMapping(value = "export")
    public void Export(HttpServletResponse response) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("User表");
        List<User> list = userService.selectAll();
        // 设置要导出的文件的名字
        String fileName = "users"  + new Date() + ".xls";

        // 新增数据行，并且设置单元格数据
        int rowNum = 1;

        // headers表示excel表中第一行的表头 在excel表中添加表头
        String[] headers = { "id", "用户名", "地址"};
        HSSFRow row = sheet.createRow(0);
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (User item : list) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(item.getId());
            row1.createCell(1).setCellValue(item.getUsername());
            row1.createCell(2).setCellValue(item.getAddress());
            rowNum++;
        }
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.flushBuffer();
        workbook.write(response.getOutputStream());
    }

    @RequestMapping("/error")
    @ResponseBody
    public String error(){
        int num=1/0;
        return null;
    }
}
